package org.springforge.ldap.service.impl.connexion;

import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class jndiManagerConnection {
	/*
	 * Contexte inital
	 */
	public final static String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory";
	
	/*
	 * Machine + port du serveur LDAP
	 */
	public final static String URL = "ldap://127.0.0.1:389";
	
	/*
	 * Authentification parameters connection
	 */
	public final static String AUTHENTIFICATION = "simple";
	
	/*
	 * LDap base connection
	 */
	public final static String LDAP_ADMIN_DN = "cn=admin, dc=forge, dc=org";
	public final static String LDAP_AUTH_DN = "dc=forge,dc=org";
	
	/*
	 * LDap credential for admin connection
	 */
	public final static String ADMIN_CREDENTIALS = "admin";
	public final static String AUTH_CREDENTIALS = "admin";
	
	
	
	/**
	 * This method used to get the DirContext through the JNDI API
	 * @return DirContext
	 * @throws NamingException
	 */
	public DirContext getLDAPDirContext() throws NamingException{
	    final Hashtable<Object, Object> envValues = new Hashtable<Object,Object>();
	    // Assign the JNDI environment values in Map
	    envValues.put(Context.INITIAL_CONTEXT_FACTORY,INITCTX);
	    envValues.put(Context.PROVIDER_URL, URL);
	    envValues.put(Context.SECURITY_AUTHENTICATION,AUTHENTIFICATION);
	    envValues.put(Context.SECURITY_PRINCIPAL,LDAP_ADMIN_DN); // specify the username
	    envValues.put(Context.SECURITY_CREDENTIALS,ADMIN_CREDENTIALS);           // specify the password
	    // Specify timeout to be 5 seconds
		envValues.put("com.sun.jndi.ldap.connect.timeout", "5000");
			
	    return new InitialDirContext(envValues);
	}
	
	
	public DirContext getAuthLDAPDirContext(String username, String password) throws NamingException,AuthenticationException{
	    final Hashtable<Object, Object> envValues = new Hashtable<Object,Object>();
	    // Assign the JNDI environment values in Map
	    envValues.put(Context.INITIAL_CONTEXT_FACTORY,INITCTX);
	    envValues.put(Context.PROVIDER_URL, URL);
	    envValues.put(Context.SECURITY_AUTHENTICATION,AUTHENTIFICATION);
	    envValues.put(Context.SECURITY_PRINCIPAL,"mail="+username+",ou=users,dc=forge,dc=org"); // specify the username
	    envValues.put(Context.SECURITY_CREDENTIALS,password);  // specify the password
	    // Specify timeout to be 5 seconds
		envValues.put("com.sun.jndi.ldap.connect.timeout", "5000");
	    return new InitialDirContext(envValues);
	}
	
	
	
	public void disConnectLDAPConnection(DirContext dirCtx)throws NamingException{
		dirCtx.close();
	}
	
}